﻿#include<iostream>
class blut {
	bool bUse = true;
public:
	float x;
	float h;
	float y;

	float damage;

	void* operator new(size_t size);//重载new
	void operator delete(void* adr)noexcept;//重载delete，noexcept修饰的函数不会抛出异常，定义这个版本后其他版本永不调用

	void* operator new(size_t size, const char* txt);
	void operator delete(void* adr, size_t size)noexcept;

	void* operator new[](size_t size) = delete;//删除不要的版本
	void operator delete[](void* adr) = delete;//删除不要的版本

	~blut();
};
char* mem = new char[1000 * sizeof(blut)] {};

void* blut::operator new(size_t size) {//size为要分配的内存空间，这里表示为类的大小，静态函数，因为内存还没分配没有this指针
	//return new blut;//会造成死循环
	//return ::operator new (size);//::表示全局命名空间，operator new 表示全局new
	//return mem;//分配到指定位置上
	blut* dat = (blut*)mem;
	for (int i = 0; i < 1000; i++) {
		if (!dat[i].bUse)return &dat[i];
	}
}

void blut::operator delete(void* adr)noexcept {//adr表示释放的指针，静态函数，因为已经调用了析构函数没有空间了，也就没有了this指针

}

void* blut::operator new(size_t size, const char* txt) {
	blut* dat = (blut*)mem;
	for (int i = 0; i < 1000; i++) {
		if (!dat[i].bUse)return &dat[i];
	}
	std::cout << "\r\n申请分配内存！" << txt << std::endl;
	//return mem;
}
void blut::operator delete(void* adr, size_t size)noexcept {
	std::cout << "\r\n释放内存X！" << size << std::endl;
}

blut::~blut() {
	bUse = false;
}

int main() {
	//blut* shota = new((void*)0x20000) blut();//指定内存地址分配
	//blut* shota = new(mem) blut;//内存分配到mem上
	blut* shota1 = new blut;
	blut* shota2 = new blut;
	blut* shota3 = new blut;
	delete shota1;
	blut* shota4 = new blut;
	blut* shota5 = new blut;
	blut* shota6 = new blut;
	blut* shota7 = new("it's a test") blut;
	std::cout << (void*)mem << std::endl;//000001A2046A2010
	std::cout << shota1 << std::endl;//000001A2046A2010
	std::cout << shota2 << std::endl;//000001A2046A2024
	std::cout << shota3 << std::endl;//000001A2046A2038
	std::cout << shota4 << std::endl;//000001A2046A204C
	std::cout << shota5 << std::endl;//000001A2046A2060
	std::cout << shota6 << std::endl;//000001A2046A2074
	std::cout << shota7 << std::endl;//000001A2046A2088，从上得知，相差0x14字节

	delete[] mem;
	delete shota1;
	delete shota7;
}
